package org.swingDemo.helper;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.swingDemo.fileFilter.ClassifyFileFilter;

import java.io.File;
import java.util.*;

public class FileHelper {

    private static FileHelper instance = null;
    public static FileHelper getInstance() {
        if (instance == null) {
            instance = new FileHelper();
        }
        return instance;
    }

    private FileHelper() {}

    // 获取所有目录列表
    public Map<String, List<String>> getNewFolderMap() throws Exception {
        String folderMap = ClassifyOptionHelper.getFolderMap();
        List<String> allFolders = StrUtil.split(folderMap, ";");
        List<String> keyList = new ArrayList<>();
        Map<String, String> keyMap = new HashMap<>();
        for (String folder : allFolders) {
            List<String> values = StrUtil.split(folder, "=");
            if (values.size() != 2) {
                continue;
            }
            keyList.add(values.get(0));
            keyMap.put(values.get(0), values.get(1));
        }

        keyList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.compareTo(o1);
            }
        });

        Map<String, List<String>> newFolderMap = new LinkedHashMap<>();
        for (String key : keyList) {
            String value = keyMap.get(key);
            value = StrUtil.trim(value);
            List<String> containStrings = StrUtil.split(value, ',');
            newFolderMap.put(StrUtil.trim(key), containStrings);
        }
        return newFolderMap;
    }

    // 获取源目录及其子目录中的所有文件列表
    public List<File> getFileList(String folder) {
        List<File> fileList = new ArrayList<>();

        if (FileUtil.isDirectory(folder)) {
            List<File> loopFileList = FileUtil.loopFiles(folder, new ClassifyFileFilter());
            for (File loopFile : loopFileList) {
                if (FileUtil.isFile(loopFile)) {
                    fileList.add(loopFile);
                } else if (FileUtil.isDirectory(loopFile)) {
                    fileList.addAll(getFileList(loopFile.getAbsolutePath()));
                }
            }
        }

        return fileList;
    }

    // 获取文件所属的目录
    public String getNewFolderOfFile(String fileName) throws Exception {
        Map<String, List<String>> folderMap = getNewFolderMap();
        Set<Map.Entry<String, List<String>>> entries = folderMap.entrySet();
        for (Map.Entry<String, List<String>> entry : entries) {
            String folderName = entry.getKey();
            List<String> matchedValues = entry.getValue();
            for (String value : matchedValues) {
                if (fileName.toLowerCase().contains(value)) {
                    return folderName;
                }
            }
        }
        return "";
    }
}
